package com.jinghong.registerlogin.controller;
import com.jinghong.registerlogin.model.pojo.Result;
import com.jinghong.registerlogin.model.pojo.User;
import com.jinghong.registerlogin.service.UserService;
import com.jinghong.registerlogin.utils.JwtUtils;
import com.jinghong.registerlogin.utils.Md5Util;
import com.jinghong.registerlogin.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:UserController
 * Package:com.jinghong.epidemiccontrolproject.controller.UserController
 * Description:
 *
 * @Author: 寻月君子
 * @CreatTime:2023/12/18 20:19
 * Version:1.0
 */
@Validated
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp ="\\S{3,16}$") String username,@Pattern(regexp ="\\S{5,16}$") String password) {
        return userService.register(username,password);

    }

    @PostMapping("/login")
    public Result login(String username,  String password) {
        return  userService.loginByUserName(username,password);
    }



    @PutMapping ("/update")
    public Result update(@RequestBody User user){
        log.info("更新用户信息 : {}", user);
        userService.update(user);
        return Result.success();
    }


    @GetMapping("/userinfo")
    public Result userinfo(){
        log.info("通过令牌查询用户信息");
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/updatePassword")
    public Result updatePassword(String username,String oldPassword ,String password){
        return userService.updatePassword(username,oldPassword,password);
    }


}
